package com.x.epspace.common;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.QueryResults;
import org.springframework.stereotype.Service;

import com.x.epspace.dao.BindEntDao;
import com.x.epspace.dao.MessagesDao;
import com.x.epspace.entity.BindEnt;
import com.x.epspace.entity.Messages;
import com.x.epspace.entity.RegUser;
import com.x.epspace.ext.HandleSessionService;

@Service("messageService")
public class MessagesService {
	
	@Resource
	private MessagesDao messagesDao;
	
	@Resource
	private BindEntDao bindEntDao;
	
	@Resource
	private HandleSessionService handleSession;
	
	/**
	 * 根据当前登录用户查找其企业消息
	 * @return
	 */
	public List<Messages> findAllForEnt() {
		List<Messages> msgList = null;
		Object bindEntObj = handleSession.getVal(AppConfig.getProperty("ENT_SESSION_KEY","SESSION_KEY"));
		BindEnt bindEnt = (BindEnt) bindEntObj;
		
		Query<Messages> qm = messagesDao.createQuery();
		qm.field("bindEnt").equal(bindEnt);
		QueryResults<Messages> msgResults = messagesDao.find(qm);
		if(msgResults.countAll() >0 ){
			msgList = msgResults.asList();
		}
		return msgList;
	}
	
	/**
	 * 获得当前登录用户绑定企业的消息数量
	 * @param bindEnt
	 * @return
	 */
	public String getMsgCount() {
		String num = "0";
		Object regUserObj = handleSession.getVal(AppConfig.getProperty("USER_SESSION_KEY","SESSION_KEY"));
		if(regUserObj == null) return "0";
		Object bindentObj = handleSession.getVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"));
		if(bindentObj == null) return "0";
		RegUser regUser = (RegUser)regUserObj;
		BindEnt bindEnt = (BindEnt) bindentObj;
		Query<Messages> qm = messagesDao.createQuery();
		qm.field("regUser").equal(regUser).field("bindEnt").equal(bindEnt).field("isRead").equal("0");
		long numLong = messagesDao.count(qm);
		num = String.valueOf(numLong);
		return num;
	}
	
	/**
	 * 更改企业消息状态为已读
	 * @param msgId
	 */
	public void changeState(String objId) {
		ObjectId objectid = new ObjectId(objId);
		Messages msg = messagesDao.findOne("oid", objectid);
		msg.setIsRead("1");
		messagesDao.save(msg);
	}
	
}
